import device from '../../api/device'
// import { buffer2hex, uint16ToBytes } from '../../js/hexUtil'
import store from '../../store/store'
import { bus } from './bus'
class Client {
  constructor(url, keys, io) {
    console.log('初始化MQTT客户端')
    this.url = url
    this.io = io
    this.keys = keys
    this.vm = null
    this.socket = null
    this.userId = 1
    this.name = '客高端注册'
    this.roomInfo = null
    this.mqtt_client = null
    this.mqtt_init()
  }

  mqtt_init() {
    let sss = this
    let mqtt = require('mqtt')

    let options = {
      username: 'bang',
      password: 'qq2711524'
    }

    let client = mqtt.connect('mqtt://139.199.170.154:8083/mqtt', options)
    this.mqtt_client = client
    client.on('connect', function() {
      //获取我的设备列表
      //获取TOPIC
      device.deviceTopicList('1').then(res => {
        // 执行某些操作
        const arr = res.data.data
        let item
        // var startTime = uint16ToBytes(1551858779)
        // var endTime = uint16ToBytes(1551858959)
        // var dataBuffer = Buffer.concat([Buffer.from(startTime), Buffer.from(endTime)])
        // client.publish('/1001/100132/task/0/set', dataBuffer)
        for (item in arr) {
          // console.log("arr[" + index + "] = " + arr[index]);
          client.subscribe(arr[item].topic, 2, function(err) {
            if (!err) {
            }
          })
        }
        // console.info(res.data.data);
      })

      client.subscribe('/1001/+/task/+/pub', 2, function(err) {
        if (!err) {
        }
      })
      client.subscribe('/1001/+/power/pub', 2, function(err) {
        if (!err) {
        }
      })
      client.subscribe('/1001/+/mode/pub', 2, function(err) {
        if (!err) {
        }
      })
    })

    client.on('offline', function() {})

    client.on('message', function(topic, message) {
      let c = buffer2hex(message)
      let data = new Uint8Array(message)
      let topicCompoments = topic.split('/')
      let productId = topicCompoments[0]
      let deviceId = topicCompoments[1]

      console.log('mqtt recive from topic:' + topic + ' hex:' + c + ' msg:' + message.toString())
      let jsonObj = null
      let thisstore = store
      thisstore.commit('updateText', message.toString())
      try {
        bus.$emit('msg', productId, deviceId, message, topic)
        // jsonObj = JSON.parse(message.toString())
      } catch (e) {
        console.log(e.toString())
      }
    })
  }
}

export default Client
